package com.frame.pageform;


import java.lang.reflect.Method;
import java.util.*;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import ognl.Ognl;
import ognl.OgnlException;
import com.frame.database.JdataBean;
import com.frame.pageform.upload.PageFile;
import com.frame.util.*;

public class PageBeanUtil {

	public static final Class[] ecs = new Class[0];
	public static final Object[] eos = new Object[0];

	private PageForm pageform;

	public PageForm createPageForm(String reuqestUrl){
		String urlClass=UrlWriteConfig.getInstance().patternUrl(reuqestUrl);
		if(urlClass!=null && !"".equals(urlClass))
			reuqestUrl="/"+urlClass;
		reuqestUrl=reuqestUrl.replaceAll("\\/", ".");
		reuqestUrl=reuqestUrl.substring(1, reuqestUrl.length());
		if(reuqestUrl.startsWith("platform.")){
			reuqestUrl=reuqestUrl.replaceAll("platform.", "");
			reuqestUrl="com.frame.platform."+reuqestUrl;
		}
		if(!reuqestUrl.startsWith("com."))
			reuqestUrl=PageServlet.getPagepackage()+"."+reuqestUrl;
		PageForm pageform=null;
		try {
			pageform = (PageForm)Class.forName(reuqestUrl).newInstance();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			System.out.println(reuqestUrl+"不存在");
			e.printStackTrace();
		}catch(Exception e){
			System.out.println(reuqestUrl+"没有继承PageForm");
			e.printStackTrace();
		}
		return pageform;
	}
	/**
	 * 填充pageform属性值
	 *
	 */
	public void fillParameter(PageForm pageform,Map parameterMap,String contenType,String charset){
		this.pageform=pageform;
		if(contenType!=null && contenType.toLowerCase().indexOf("multipart/form-data")!=-1){
			try {
				DiskFileItemFactory factory = new DiskFileItemFactory();
				ServletFileUpload upload = new ServletFileUpload(factory);
				upload.setHeaderEncoding("utf-8");
				List items = upload.parseRequest(RequestContext.getContext().getRequest());
				Iterator iter = items.iterator();
				Map<String,List> setParmMap=new HashMap<String,List>();
				List<FileItem> fileItemList =null;
				while (iter.hasNext()) {
					FileItem item = (FileItem) iter.next();
					if (item.isFormField()) {
						try{
							List vlist=(List)setParmMap.get(item.getFieldName());
							if(vlist==null)
								vlist=new ArrayList();
							vlist.add(item.getString("utf-8"));
							setParmMap.put(item.getFieldName(), vlist);
						}
						catch(Exception e){
						}
					} else {
						if(item.getName().length()>0 && item.get().length>0){
							if(fileItemList==null)fileItemList=new ArrayList<FileItem>();
							fileItemList.add(item);
						}
					}
				}
				RequestContext.getContext().setParameterMap(setParmMap);
				RequestContext.getContext().setFileItemList(fileItemList);

				Iterator iterator = setParmMap.entrySet().iterator();
				while(iterator.hasNext())
				{
					String s="";
					try{
						Map.Entry entry = (Map.Entry)iterator.next();
						s = (String)entry.getKey();
						List list=(List)entry.getValue();
						String[] value =new String[list.size()];
						for(int m=0;m<list.size();m++){
							value[m]=list.get(m).toString();
						}
						setProperty(s,value);
					}
					catch(Exception e){
						System.out.println(s+"赋值发生错误"+e.getMessage());
					}
				}
			}catch (Exception e1) {
				e1.printStackTrace();
			}

		}else{
			Iterator iterator = parameterMap.entrySet().iterator();
			while(iterator.hasNext())
			{
				String s="";
				try{
					Map.Entry entry = (Map.Entry)iterator.next();
					s = (String)entry.getKey();
					String[] value = (String[])entry.getValue();
					setProperty(s,value);
				}
				catch(Exception e){
					System.out.println(s+"赋值发生错误"+e.getMessage());
					e.printStackTrace();
				}
			}
		}

	}
	public void setProperty(String name,PageFile[] value) throws Exception{
		String methodName = Character.toUpperCase(name.charAt(0)) +name.substring(1);
		Class c=pageform.getClass();
		Class type=BeanUtils.getType(c,name);
		Object obj=null;
		if(type == PageFile.class){
			obj = value[0];
		}
		else if(type== PageFile[].class)
			obj = value;
		Method setMethod = pageform.getClass().getMethod("set"+methodName,new Class[]{type});

		setMethod.invoke(pageform,new Object[]{obj});
	}
	public void setProperty(String name,String[] value) throws Exception{
		int n=name.indexOf(".");
		if(n!=-1){
			String parent=name.substring(0,n);
			String child=name.substring(n+1);
			String methodName = Character.toUpperCase(parent.charAt(0)) +parent.substring(1);
			Method getMethod = pageform.getClass().getMethod("get" + methodName,ecs);
			Object obj=getMethod.invoke(pageform, eos);
			Class c=getMethod.getReturnType();
			if(obj==null){
				obj=c.newInstance();
				Method setMethod = pageform.getClass().getMethod("set"+methodName,new Class[]{c});
				setMethod.invoke(pageform,new Object[]{obj});
			}
			setProperty(obj,child,value);
		}else{
			try{
				String methodName = Character.toUpperCase(name.charAt(0)) +name.substring(1);
				Class c=pageform.getClass();
				Class type=BeanUtils.getType(c,name);
				Method setMethod = pageform.getClass().getMethod("set"+methodName,new Class[]{type});
				Object obj=ConvertFactoy.convertValue(type,value);
				setMethod.invoke(pageform,new Object[]{obj});
			}
			catch(NoSuchMethodException ex){}
			catch(Exception e){throw e;}
		}
	}
	public void setProperty(Object obj,String name,String[] value) throws Exception{
		String methodName = Character.toUpperCase(name.charAt(0)) +name.substring(1);
		Class c=obj.getClass();
		try{
			if(obj instanceof JdataBean){
				JdataBean bean=(JdataBean)obj;
				if(value!=null){
					if(value.length==1)
						bean.put(name, value[0]);
					else
						bean.put(name, value);
				}
			}else{
				Class type=BeanUtils.getType(c,name);
				Method setMethod = obj.getClass().getMethod("set"+methodName,new Class[]{type});
				Object valueobj=ConvertFactoy.convertValue(type,value);
				setMethod.invoke(obj,new Object[]{valueobj});
			}
		}
		catch(NoSuchMethodException ex){}
		catch(Exception e){throw e;}
	}
	/**
	 * 执行pageForm方法
	 * @param obj
	 * @param method
	 * @param
	 * @return
	 */
	public String execMethods(Object obj,Method method) throws Exception{
		Class c=obj.getClass();
//		Method method = null;
//		Method[] methods = c.getMethods();
//		for(int i = 0; i < methods.length; i++)
//		{
//         if(methodName.equals(methods[i].getName()))
//         {
//            method = methods[i];
//            break;
//         }
//		}
//		if(method == null)
//			throw new Exception("方法" + c.getName() + "." + methodName + "不存在");
		Map parameterMap=RequestContext.getContext().getRequest().getParameterMap();
		Class[] parameterTypes =method.getParameterTypes();
		Object[] parameters=new Object[parameterTypes.length];
		for(int i=0;i<parameterTypes.length;i++){
			String pn="@p"+i;
			String[] value=(String[])parameterMap.get(pn);
			if(value!=null){
				Object valueobj=ConvertFactoy.convertValue(parameterTypes[i],value);
				parameters[i]=valueobj;
			}
		}
		Object reobj=method.invoke(obj, parameters);
		if(reobj!=null)
			return reobj.toString();
		else
			return null;
	}

	/**
	 * 获得属性类型
	 * @param name
	 * @param c
	 * @return
	 * @throws Exception
	 */
	public Class getPropertyType(String name,Class c) throws Exception{
		int n = name.indexOf(".");
		String s1="",s2="";
		if(n!=-1){
			s1=name.substring(0,n);
			s2=name.substring(n+1);
		}else{
			s1=name;
			s2=null;
		}
		String methodName = Character.toUpperCase(s1.charAt(0)) + s1.substring(1);
		Method method=null;
		try{
			method=c.getMethod("get"+methodName, ecs);
		}catch(Exception e){
			try {
				method=c.getMethod("is"+methodName, ecs);
			} catch (Exception e1) {
				e1.printStackTrace();
				throw new Exception(e1);
			}
		}
		if(s2==null)
			return method.getReturnType();
		else{
			c=method.getReturnType();
			return getPropertyType(s2,c);
		}
	}
	public static Object getOgnlValue(String expression,Object obj,Map context) throws OgnlException{
		int n=expression.indexOf(".");
		if(n!=-1){
			//判断第一个对象是否为空，为空则退出不执行下一步
			String s1=expression.substring(0,n);
			Object obj1=getOgnlValue(s1,obj,context);
			if(obj1 == null) {
				return null;
			} else if(obj1 instanceof JdataBean){
				JdataBean bean=(JdataBean)obj1;
				String s2=expression.substring(n+1);
				int n2=s2.indexOf(".");//判断是否还有.
				if(n2!=-1){
					Object obj2=bean.get(s2.substring(0,n2));
					return getOgnlValue(s2.substring(n2+1),obj2,context);
				} else {
					return bean.get(s2);
				}
			}
		}
		if(context==null)
			return Ognl.getValue(expression,obj);
		else
			return Ognl.getValue(expression,context,obj);

	}
	public PageForm getPageform() {
		return pageform;
	}
	public void setPageform(PageForm pageform) {
		this.pageform = pageform;
	}

}
